// services/githubService.js
import { Octokit } from '@octokit/rest';

export class GitHubService {
  constructor(accessToken) {
    this.octokit = new Octokit({
      auth: 'WxW99YvdqhHdJrDyQ_nw'
    });
  }

  async getPullRequest(owner, repo, prNumber) {
    try {
      const response = await this.octokit.pulls.get({
        owner,
        repo,
        pull_number: prNumber
      });
      return response.data;
    } catch (error) {
      console.error('GitHub API Error:', error);
      throw error;
    }
  }

  async getPullRequestFiles(owner, repo, prNumber) {
    try {
      const response = await this.octokit.pulls.listFiles({
        owner,
        repo,
        pull_number: prNumber
      });
      return response.data;
    } catch (error) {
      console.error('GitHub API Error:', error);
      throw error;
    }
  }

  async getFileContent(owner, repo, path, ref) {
    try {
      const response = await this.octokit.repos.getContent({
        owner,
        repo,
        path,
        ref
      });
      
      if (response.data.content) {
        return Buffer.from(response.data.content, 'base64').toString('utf-8');
      }
      return null;
    } catch (error) {
      console.error('GitHub API Error:', error);
      return null;
    }
  }

  async createReviewComment(owner, repo, prNumber, commitId, path, body, line) {
    try {
      const response = await this.octokit.pulls.createReviewComment({
        owner,
        repo,
        pull_number: prNumber,
        commit_id: commitId,
        path,
        body,
        line,
        side: 'RIGHT'
      });
      return response.data;
    } catch (error) {
      console.error('GitHub API Error:', error);
      throw error;
    }
  }

  async createReview(owner, repo, prNumber, body, event = 'COMMENT') {
    try {
      const response = await this.octokit.pulls.createReview({
        owner,
        repo,
        pull_number: prNumber,
        body,
        event
      });
      return response.data;
    } catch (error) {
      console.error('GitHub API Error:', error);
      throw error;
    }
  }
}